package com.youkeda.yikao.web.control;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;

/**
 * @author ：xiong
 * @date ：Created in 2019/9/6 14:32
 * @description：邮箱验证
 * @modified By：
 */
@Controller
public class EmailControl {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private DefaultKaptcha kaptcha;
    //发送邮件
    @RequestMapping(path = "/sendemail")
    @ResponseBody
    public void send(HttpSession session ,@RequestParam("email") String email){
        MimeMessage message=mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper=new MimeMessageHelper(message,true);
            helper.setFrom("xionghjwy@163.com");
            helper.setTo(email);
            helper.setSubject("主题：验证码");
            String code=kaptcha.createText();
            session.setAttribute("emailcode",code);
            message.setText("<h1>"+code+"<h1>","utf-8","html");
            mailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //验证短信验证码是否正确
    @RequestMapping(path = "checkemailcode")
    @ResponseBody
    public static boolean check(@SessionAttribute(value = "emailcode",required = false) String sessionEmailCode,HttpSession  session,
                        @RequestParam("verEmail") String emailcode){
        if (emailcode.equals(sessionEmailCode)){
            session.removeAttribute("emailcode");
            return true;
        }else {
            return false;
        }
    }

}
